# 需先自行安装FFmpeg，并添加环境变量
import cv2
import subprocess
import errno

# from signal import signal, SIGPIPE, SIG_DFL
# signal(SIGPIPE,SIG_DFL)

# RTMP服务器地址
url = "rtsp://admin:abc123456789@192.168.1.65/Streaming/Channels/2"
rtsp="rtsp://admin:admin@10.152.178.3:8554/live"
rtmp = r'rtmp://127.0.0.1:1935/live/home'
# 读取视频并获取属性
cap = cv2.VideoCapture(url)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
sizeStr = str(size[0]) + 'x' + str(size[1])
command = ['ffmpeg',
           '-y', '-an',
           '-f', 'rawvideo',
           '-vcodec', 'rawvideo',
           '-pix_fmt', 'bgr24',
           '-s', sizeStr,
           '-r', '25',
           '-i', '-',
           '-c:v', 'libx264',
           '-pix_fmt', 'yuv420p',
           '-preset', 'ultrafast',
           '-f', 'flv',
           rtmp]
pipe = subprocess.Popen(command, shell=False, stdin=subprocess.PIPE
                        )
while cap.isOpened():
    success, frame = cap.read()
    if success:
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        try:
            pipe.stdin.write(frame.tobytes())
        except IOError as e:
            if e.errno == errno.EPIPE:
                pass
                # Handling of the error

cap.release()
pipe.terminate()